﻿using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;

namespace Magic.System;

[Injection]
public class ClickCaptchaService : IClickCaptchaService
{
    private readonly IMemberCacheService _cache;
    private readonly IWebHostEnvironment _environment;

    public ClickCaptchaService(IMemberCacheService cache, IWebHostEnvironment environment)
    {
        this._cache = cache;
        this._environment = environment;
    }

    public async Task CheckClickCaptcha(CheckClickCaptchaInput input)
    {
        CaptchaStateModel sItem = new CaptchaStateModel
        {
            Id = input.Id,
            DataCode=input.Info
        };
        CaptchaVerifyModel vItem = new CaptchaVerifyModel
        {
            Id = input.Id,
            Type = "TouchLetter",
            DataCode = await _cache.Get(input.Id)

        };
        
        var result = CaptchaHelper.Verify(sItem, vItem);
        if (!result.IsSuccess)
            throw new ApiException("验证码错误");
    }

    public async Task<ClickCaptchaOutput> ClickCaptcha(ClickCaptchaInput input)
    {
        byte[] imgMap = null;
        //var assembly = Assembly.GetExecutingAssembly();
        //var resourceId = assembly.GetName().Name + ".captchaLetter.png";

        var imageIndex = new Random().Next(1, 5);

        var templatePath = Path.Combine(_environment.WebRootPath, $"captchaLetter{imageIndex}.jpg");

        using (Stream stream = new FileStream(templatePath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            imgMap = new byte[stream.Length];
            stream.Read(imgMap, 0, imgMap.Length);
            stream.Seek(0, SeekOrigin.Begin);
            stream.Close();
            stream.Dispose();
        }

        var kvItem = CaptchaHelper.TouchLetter(imgMap,5);
        var imgBase64 = kvItem.Key.Image_Base64.Substring(kvItem.Key.Image_Base64.IndexOf(',') + 1);
        List<LetterLocationModel> dataCode = JsonConvert.DeserializeObject<List<LetterLocationModel>>(kvItem.Value.DataCode);

        //缓存验证码答案
        await _cache.Set(input.Id, kvItem.Value.DataCode,TimeSpan.FromSeconds(120));


        return new ClickCaptchaOutput
        {
            Id = input.Id,
            Height = 200,
            Width = 350,
            Text =dataCode.Select(m=>m.Letter).ToArray(),
            Base64 = $"data:image/png;base64,{imgBase64}",
            Codes= kvItem.Value.DataCode
        };

    }
}
